<template>
  <div class="page">
    <h3>{{ isNew ? '新建生态主题活动' : '生态主题活动' }}</h3>
    <el-steps :active="isNew ? 1 : !isEdit ? 3 : 2" align-center>
      <el-step title="填写活动并提交" />
      <el-step title="平台审核活动" />
      <el-step title="审核通过并发布/审核不通过并打回" />
    </el-steps>
    <h3>活动基础信息</h3>

    <el-result
      v-if="status == 2"
      icon="success"
      title="审核通过！"
      sub-title="活动将发布到【青少年守护者小程序】-【首页】！"
    >
      <template #extra>
        <el-button type="primary" @click="onSee">去修改活动</el-button>
      </template>
    </el-result>
    <el-result
      v-if="status == 1"
      icon="error"
      title="审核不通过！"
      sub-title="机构通过【机构端】-【活动管理】-【生态主题活动】可看到审核结果，平台也可通过微信或电话提醒发布人！"
    >
      <template #extra>
        <el-button type="primary" @click="onSee">查看活动</el-button>
      </template>
    </el-result>

    <el-form
      ref="editFormRef"
      v-if="status == 0"
      v-loading="loading"
      :model="formData"
      label-width="160px"
      :rules="formRules"
    >
      <template v-if="isEdit">
        <el-form-item label="活动名称" prop="activityName">
          <el-input
            v-model="formData.activityName"
            placeholder="输入活动名称，限制30字以内"
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="活动封面" prop="activityCover">
          <ImageUpload
            v-model="formData.activityCover"
            width="690"
            height="360"
            otherTip=",否则可能导致图片显示不佳被拒审"
          ></ImageUpload>
        </el-form-item>
        <el-form-item label="活动详情" prop="activityDetails">
          <Rich
            v-model="formData.activityDetails"
            placeholder="建议直接上传长图，支持.jpg、jpeg、.png格式尺寸上传要求：宽1035px，高度不限"
          ></Rich>
        </el-form-item>
        <el-form-item label="活动有效期" prop="activityTime">
          <div>
            <el-date-picker
              v-model="formData.activityTime"
              type="daterange"
              range-separator="至"
              style="width: 350px"
            />
          </div>
        </el-form-item>
        <el-form-item label="活动时间及人数限制" prop="detailList">
          <div
            style="display: flex; margin-right: 10px"
            :key="index"
            v-for="(item, index) in formData.detailList"
          >
            <div>
              <div>活动时间{{ index + 1 }}</div>
              <el-date-picker
                style="width: 220px"
                v-model="formData.detailList[index].time1"
                type="daterange"
              />
              <el-time-picker
                style="width: 160px"
                v-model="formData.detailList[index].time2"
                is-range
                arrow-control
                range-separator="至"
                format="HH:mm"
              />
            </div>
            <div style="margin: 0 10px">
              <div>可报名人数{{ index + 1 }}</div>
              <el-input-number
                style="width: 190px"
                placeholder="请输入可报名人数"
                v-model="formData.detailList[index].participantsLimit"
                controls-position="right"
                :min="1"
                :precision="0"
              />
              人
            </div>

            <div style="display: flex; align-items: center; padding-top: 20px">
              <ElButton
                type="danger"
                circle
                v-if="formData.detailList.length > 1"
                @click="formData.detailList.splice(index, 1)"
              >
                <template #icon>
                  <SvgIcon name="i-ep:delete" />
                </template>
              </ElButton>

              <ElButton
                type="success"
                circle
                @click="formData.detailList.splice(index + 1, 0, {})"
              >
                <template #icon>
                  <SvgIcon name="i-ep:plus" />
                </template>
              </ElButton>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="活动地点" prop="eventLocation">
          <el-input
            v-model="formData.eventLocation"
            placeholder="请输入活动地点，限制50字以内"
            type="textarea"
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item label="活动单价" prop="activityPrice">
          <el-input-number
            style="width: 190px; margin-right: 4px"
            placeholder="输入活动单价"
            v-model="formData.activityPrice"
            controls-position="right"
            :min="0"
            :precision="2"
          />
          元
        </el-form-item>
        <el-form-item label="活动分类" prop="activityType">
          <el-radio-group v-model="activityType">
            <el-radio :label="activityCategoryName" :value="1" />
            <el-radio label="线上活动" :value="-1" />
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="发起单位"
          prop="originatingComp"
          v-if="visibleOriginatingComp"
        >
          <el-input
            v-model="formData.originatingComp"
            placeholder="请输入发起单位，如：由《关注森林组委会》发起"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属任务分类" prop="classificationIds">
          <ApiSelect
            clearable
            multiple
            v-model="formData.classificationIds"
            apiName="classification"
            :config="{
              onSuccess(res) {
                classificationList = res;
              },
            }"
          ></ApiSelect>
        </el-form-item>
        <el-form-item label="活动时长" prop="activityDuration">
          <el-input-number
            style="width: 190px; margin-right: 4px"
            placeholder="请输入活动时长"
            v-model="formData.activityDuration"
            controls-position="right"
            :min="0"
            :precision="2"
          />
          小时
        </el-form-item>
        <el-form-item label="积累生态时长" prop="duration">
          <el-input-number
            style="width: 190px; margin-right: 4px"
            v-model="formData.duration"
            controls-position="right"
            :min="0"
            :precision="2"
            :disabled="activityType !== -1"
          />
          小时
        </el-form-item>
        <el-form-item label="积累生态积分" prop="integral">
          <el-input-number
            style="width: 190px; margin-right: 4px"
            v-model="formData.integral"
            controls-position="right"
            :min="0"
            :precision="2"
            :disabled="activityType !== -1"
          />
          分
        </el-form-item>

        <el-form-item label="微信咨询二维码" prop="consultationQrCode">
          <ImageUpload
            v-model="formData.consultationQrCode"
            notip
          ></ImageUpload>
        </el-form-item>
        <h3>使用须知</h3>
        <el-form-item label="使用方法" prop="usageInfo">
          <el-input
            v-model="formData.usageInfo"
            placeholder="请输入使用方法，限制300字以内"
            type="textarea"
            maxlength="300"
          ></el-input>
        </el-form-item>
        <el-form-item label="集合地址" prop="collectionAddress">
          <el-input
            v-model="formData.collectionAddress"
            placeholder="请输入集合地址，限制50字以内"
            type="textarea"
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item label="任务流程" prop="taskProcess">
          <el-input
            v-model="formData.taskProcess"
            placeholder="请输入任务流程，限制500字以内"
            type="textarea"
            maxlength="500"
          ></el-input>
        </el-form-item>
        <el-form-item label="注意事项" prop="mattersNeeding">
          <el-input
            v-model="formData.mattersNeeding"
            placeholder="请输入温馨提示，限制100字以内"
            type="textarea"
            maxlength="100"
          ></el-input>
        </el-form-item>
        <el-form-item label="取消条款" prop="cancelDays">
          活动开始
          <el-input-number
            style="width: 190px; margin: 0 4px"
            v-model="formData.cancelDays"
            controls-position="right"
            :min="0"
            :precision="0"
            placeholder="建议4~7天"
          />
          天前可免费取消
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="活动名称" prop="organizationId">
          {{ data?.activityName }}
        </el-form-item>
        <el-form-item label="活动封面" prop="organizationId">
          <el-image
            :src="data?.activityCover"
            :preview-src-list="[data?.activityCover]"
          ></el-image>
        </el-form-item>
        <el-form-item label="活动详情" prop="activityDetails">
          <div
            v-html="data?.activityDetails"
            style="border: 1px solid #ccc; padding: 10px"
          ></div>
        </el-form-item>
        <el-form-item label="活动有效期" prop="realName">
          {{ data?.activityBeginTime }} 至 {{ data?.activityEndTime }}
        </el-form-item>
        <el-form-item label="活动时间及人数限制" prop="realName">
          <el-table :data="data?.detailList || []" border>
            <el-table-column prop="date" label="活动时间">
              <template #default="scope">
                {{ scope.row.beginTime }} ~ {{ scope.row.endTime }}
              </template>
            </el-table-column>
            <el-table-column prop="participantsLimit" label="可报名人数">
              <template #default="scope">
                {{ scope.row.participantsLimit }}人
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="活动地点" prop="realName">
          {{ data?.eventLocation }}
        </el-form-item>
        <el-form-item label="活动单价" prop="realName">
          {{ toPrice(data?.activityPrice) }}
        </el-form-item>
        <el-form-item label="所属任务分类" prop="realName">
          {{ getClassificationName(data?.classificationList) }}
        </el-form-item>

        <el-form-item label="活动分类" prop="realName">
          <tag :value="data?.activityType" type="orgResourceType"></tag>
        </el-form-item>

        <el-form-item
          label="发起单位"
          prop="realName"
          v-if="visibleOriginatingComp"
        >
          {{ data?.originatingComp }}
        </el-form-item>

        <el-form-item label="活动时长" prop="realName">
          {{ data?.activityDuration }}小时
        </el-form-item>
        <el-form-item label="积累生态时长" prop="realName">
          {{ data?.duration }}小时
        </el-form-item>
        <el-form-item label="积累生态积分" prop="realName">
          {{ data?.integral }}分
        </el-form-item>

        <el-form-item label="微信咨询二维码" prop="realName">
          <el-image
            style="width: 200px"
            :src="data?.consultationQrCode"
            :preview-src-list="[data?.consultationQrCode]"
          ></el-image>
        </el-form-item>
        <h3>使用须知</h3>
        <el-form-item label="使用方法" prop="realName">
          {{ data?.usageInfo }}
        </el-form-item>
        <el-form-item label="集合地址" prop="realName">
          {{ data?.collectionAddress }}
        </el-form-item>
        <el-form-item label="任务流程" prop="realName">
          {{ data?.taskProcess }}
        </el-form-item>
        <el-form-item label="注意事项" prop="realName">
          {{ data?.mattersNeeding }}
        </el-form-item>
        <el-form-item label="取消条款" prop="sex">
          活动开始{{ data?.cancelDays }}天前可免费取消
        </el-form-item>
      </template>

      <div v-if="data">
        <h3>活动审核</h3>
        <el-form-item label="申请人" prop="realName">
          {{ data?.createByName }}
        </el-form-item>
        <el-form-item label="申请时间" prop="realName">
          {{ data?.createTime }}
        </el-form-item>

        <el-form-item label="审核状态" prop="status">
          <tag
            :value="data?.auditingStatus"
            type="auditingStatus"
            style="min-width: 68px"
          ></tag>
        </el-form-item>
        <el-form-item label="是否上线" prop="auditingStatus">
          <el-switch
            v-model="formData.status"
            active-text="上线"
            inactive-text="下线"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <!-- 未审核 -->
        <div v-if="data.auditingStatus == 0"></div>
        <!-- 已通过 -->
        <div v-if="data.auditingStatus == 2">
          <el-form-item label="审核时间" prop="status">
            {{ data?.updateTime }}
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm"> 提交 </el-button>
            <el-button @click="$router.back()">取消 </el-button>
          </el-form-item>
        </div>
        <!-- 美通过 -->
        <div v-if="data.auditingStatus == 1">
          <el-form-item label="审核时间" prop="status">
            {{ data?.updateTime }}
          </el-form-item>
          <el-form-item label="打回理由" prop="status">
            <el-input
              disabled
              :value="data?.auditingReason || ' '"
              :rows="2"
              type="textarea"
              placeholder="请输入打回理由"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="$router.back()"
              >我知道了
            </el-button>
          </el-form-item>
        </div>
      </div>
      <el-form-item v-if="isEdit">
        <el-button type="primary" @click="editSubmitForm"> 提交 </el-button>
        <el-button @click="$router.back()">取消 </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import API from '@/api/api';
import { useMessage } from '@/hooks/useMessage';
import useUserStore from '@/store/modules/user';
import dayjs from '@/utils/dayjs';
import { toPrice, getClassificationName, formatDate } from '@/utils/index';
import { createRequireRole } from '@/utils/rules';
import { useRequest } from 'vue-hooks-plus';
import initValue from './initValue';
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const isNew = ref(!route.query.id);
// 0 正常状态   1 提交审核是失败 2 提交审核成功
const status = ref(0);
const isEdit = computed(() => {
  if (isNew.value) {
    return true;
  }
  if (!(data.value?.auditingStatus == 2)) {
    return true;
  }
  return false;
});
const activityType = ref(1);
const classificationList = ref([]);
const activityCategoryName = computed(() => {
  let orgResourceType = userStore.userInfo?.orgResourceType;
  if (orgResourceType == 0) {
    // 公益
    if (formData.activityPrice == 0) {
      return '公益';
    } else {
      return '精选';
    }
  } else {
    // 盈利
    return '精选';
  }
});
const visibleOriginatingComp = computed(() => {
  let orgResourceType = userStore.userInfo?.orgResourceType;
  return orgResourceType == 0 && formData.activityPrice == 0;
});
function transformDataToView(value: any) {
  return {
    ...value,
    classificationIds: (value.classificationList || []).map(item => item.id),
    activityTime: [
      dayjs(value.activityBeginTime).toDate(),
      dayjs(value.activityEndTime).toDate(),
    ],
    activityBeginTime: dayjs(value.activityBeginTime).toDate(),
    activityEndTime: dayjs(value.activityEndTime).toDate(),
    activityPrice: value.activityPrice / 100,
    detailList: !value.activityDetailJSON?.length
      ? [{}]
      : value.activityDetailJSON.map(item => {
          return {
            ...item,
            time1: [
              dayjs(item.beginTime).toDate(),
              dayjs(item.endTime).toDate(),
            ],
            time2: [
              dayjs(item.beginTime).toDate(),
              dayjs(item.endTime).toDate(),
            ],
          };
        }),
  };
}

function transformDataToSend(value: any) {
  function getDateWithTwoDate(date1: any, date2: any) {
    return formatDate(
      dayjs(date1).format('YYYY-MM-DD') + dayjs(date2).format(' HH:mm:00')
    );
  }
  return {
    ...value,
    detailList: undefined,
    activityDetailList: undefined,
    onlineType: activityType.value == -1 ? 1 : 0,
    activityPrice: value.activityPrice * 100,
    classificationList: undefined,
    activityBeginTime: formatDate(value.activityTime[0]),
    activityEndTime: formatDate(value.activityTime[1]),
    activityDetailJSON: value.detailList.map(item => {
      return {
        participantsLimit: item.participantsLimit,
        id: item.id,
        activityBeginTime: getDateWithTwoDate(item.time1[0], item.time2[0]),
        activityEndTime: getDateWithTwoDate(item.time1[1], item.time2[1]),
      };
    }),
  };
}
const formRules = reactive({
  activityName: [createRequireRole()],
  activityCover: [createRequireRole()],
  activityDetails: [createRequireRole()],
  auditingStatus: [createRequireRole()],
  activityBeginTime: [createRequireRole()],
  detailList: [createRequireRole()],
  eventLocation: [createRequireRole()],
  activityPrice: [createRequireRole()],
  originatingComp: [createRequireRole()],
  classificationIds: [createRequireRole()],
  activityDuration: [createRequireRole()],
  duration: [createRequireRole()],
  integral: [createRequireRole()],
  usageInfo: [createRequireRole()],
  collectionAddress: [createRequireRole()],
  taskProcess: [createRequireRole()],
  mattersNeeding: [createRequireRole()],
  cancelDays: [createRequireRole()],
  activityTime: [createRequireRole()],
});
let formData = reactive({
  detailList: [{}],
  // ...transformDataToView(initValue),
});
watch(
  () => formData.activityDuration + formData.classificationIds,
  value => {
    // 积累生态时长*
    formData.duration = Math.ceil(formData.activityDuration / 2);
    if (Array.isArray(formData.classificationIds)) {
      // 积累生态积分*
      formData.integral = formData.classificationIds
        .map(id => {
          return (
            classificationList.value.find(item => item.id == id)?.integral || 0
          );
        })
        .reduce((num, item) => {
          return num + item;
        }, 0);
    }
  }
);

function checkDate(value) {
  if (!formData.activityBeginTime) return true;
  return (
    dayjs(value).isBefore(dayjs(formData.activityBeginTime)) ||
    dayjs(value).isAfter(dayjs(formData.activityEndTime))
  );
}
const formRef = ref(); // 表单 Ref
const editFormRef = ref(); // 表单 Ref

const message = useMessage(); // 消息弹窗

const updateOnlineReq = useRequest(
  async (sendData: any) => {
    return API.activityController.updateonline({
      id: route.query.id,
      status: formData.status,
    });
  },
  {
    manual: true,
  }
);
const editSubmitReq = useRequest(
  async (sendData: any) => {
    if (isNew.value) {
      return API.activityController.add({
        ...sendData,
        activityType: visibleOriginatingComp?.value ? 0 : 1,
      });
    }
    return API.activityController.update({
      id: route.query.id,
      ...sendData,
    });
  },
  {
    manual: true,
  }
);
function onSee() {
  status.value = 0;
  refresh();
}
const submitForm = async () => {
  await updateOnlineReq.runAsync(formData);
  message.success('提交成功!');
  router.back();
};

async function editSubmitForm() {
  // 校验表单
  if (!editFormRef) return;

  const valid = await editFormRef.value.validate();

  for (let [index, item] of formData.detailList.entries()) {
    if (!item.time1 || !item.time2?.length) {
      return message.error(`请填写第${index + 1}行可报名时间段`);
    }
    if (!item.participantsLimit) {
      return message.error(`请填写第${index + 1}行可报名人数`);
    }
  }

  await editSubmitReq.runAsync(transformDataToSend(formData));
  if (isNew.value) {
    message.success('创建成功!');
  } else {
    message.success('修改成功!');
  }
  router.back();
}

const { data, loading, refresh } = useRequest(
  async () => {
    return API.activityController.info({
      id: route.query.id,
    });
  },
  {
    ready: !!route.query.id,
    onSuccess(res) {
      Object.entries(transformDataToView(res)).map(([key, value]) => {
        formData[key] = value;
      });
    },
  }
);
</script>
